/*时钟*/
import React, { Component } from 'react';

import { addZero } from "../../util";

import './style.less';

class Clock extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: ''
    };
    this.getCurrentTime = this.getCurrentTime.bind(this);
  }

  render() {
    return (
      <p className="pinlor-clock">{this.state.time}</p>
    )
  }

  componentDidMount() {
    // 获取当前时间
    this.getCurrentTime();
    // 每秒更新一次
    this.timer = setInterval(this.getCurrentTime, 1000);
  }

  componentWillUnmount() {
    // 组件卸载时，清除定时器
    clearInterval(this.timer);
  }

  getCurrentTime() {
    // 获取当前时间
    const date = new Date();
    const year = date.getFullYear();
    const month = addZero(date.getMonth() + 1);
    const day = addZero(date.getDate());
    const hour = addZero(date.getHours());
    const minute = addZero(date.getMinutes());
    const second = addZero(date.getSeconds());
    this.setState({
      time: `${year}年${month}月${day}日 ${hour}:${minute}:${second}`
    })
  }
}

export default Clock;
